#include "widget.h"
#include "ui_widget.h"
#include <map>
#include <utility>
#include <iostream>
#include <iterator>
#include <QListWidgetItem>
#include <QScrollBar>
using namespace std;
int fd1[2];
QString timeover;
int timeaft;
map<int,QString> maps;

void * getTimeLens(void * arg){
    while(1){
        ::close(fd1[1]);
        char buf[64] = {0};
        read(fd1[0] ,buf,sizeof(buf));
        char * p = strstr(buf,"ANS_LENGTH");
        if(p != NULL){

             char * q = strchr(p,'.');
             *q = '\0';
             timeover = p+11;

             timeaft = timeover.toInt();
             qDebug()<< timeaft;
        }

    }
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    maps.clear();
    ui->setupUi(this);
    this->setWindowTitle("咕咚音乐");
    timer = new QTimer;
    ui->time1->setStyleSheet("color: #F5F5F5");
    ui->time2->setStyleSheet("color: #F5F5F5");
    connect(timer,&QTimer::timeout,this,&Widget::setTime);
    listfun();
    index = 2;
//    QString strStyle = "QListWidget{font-size:10px; font-family:Microsoft YaHei UI;  " //字体大小，边框
//            "padding-left:10px;"
//            /*列表项文本设置*/
//            "QListWidget::item{height:40px; }" //设置每行行高
//            /*列表项扫过时文本、背景变化*/
//            "QListWidget::item:hover{color:#FF8AAA; background:#FFB6C1;}"
//            /**列表项选中*/
//            "QListWidget::item::selected{ color:#4f7d8b; background:transparent;}"
//            ;
    connect(ui->listWidget_2->verticalScrollBar(), SIGNAL(valueChanged(int)),this,SLOT(onStudyValueChanged(int)));
//    ui->bfbtn->setStyleSheet("QPushButton{border:hideen}");
    ui->listWidget_2->setFixedSize(400,260);
    ui->listWidget_2->horizontalScrollBar()->hide();
    ui->listWidget_2->verticalScrollBar()->hide();
    ui->listWidget->horizontalScrollBar()->hide();
    ui->listWidget->verticalScrollBar()->hide();
    ui->listWidget->setCurrentRow(index);
    ui->horizontalSlider_2->setValue(80);
    ui->listWidget_2->setFrameShape(QListWidget::NoFrame);
    ui->listWidget->setFrameShape(QListWidget::NoFrame);
    ui->listWidget->setStyleSheet(" QListView { background-color: transparent; } QListWidget::item { color: #F5F5F5;height:30px; }QListView::item { color: #A5AA55;} QListWidget::item::selected{ font-size:14px; color:#F5F5F5; background:transparent;}");
    ui->listWidget_2->setStyleSheet(" QListView { background-color: transparent; } QListWidget::item{height:30px; padding-left:0;}QListView::item { color: #229977;} QListWidget::item::selected{ font-size:12px; color:#22EEAA; background:transparent;}");
    timebef = 0;
    tag = 2;
    flag = 0;
    mygqname = ui->listWidget->item(index)->text();
    gcshow();
    getgc(NULL,0);
    pipe(fd1);
    dup2(fd1[1],1);

    int pid = fork();
    if(pid == 0){
        execlp("mplayer",
                    "mplayer",
                    "-slave","-quiet","-idle",
                    "-input","file=./fifo_cmd",
                    NULL);
         exit(0);
    }else if(pid > 0){
        mypid = pid;
        pthread_t t1;
        pthread_create(&t1,NULL,getTimeLens,this);
    }

}

void Widget::paintEvent(QPaintEvent *event)//背景
{
       QPainter p(this);
       QPixmap pix;
       pix.load(":/img/6.jpg");
       pix.scaled(this->width(),this->height());
       p.drawPixmap(0,0,this->width(),this->height(),pix);
}

void Widget::listfun()//初始化歌曲列表
{
    maxindex = 0;
    DIR *dir = opendir("/home/zjr/znyx/song");
    if(dir == NULL){
        printf("123\n");
        return ;
    }
    while (1) {
        struct dirent * d = readdir(dir);
        if(d == NULL){
            break;
        }
        if(d->d_type == DT_REG){
            maxindex++;
            ui->listWidget->addItem(d->d_name);
        }
    }
    closedir(dir);
    return;
}

void Widget::bfyyfun(char mycontrol[])//遥控器
{
        char buf[100]= {0};
        strcpy(buf,mycontrol);
        buf[strlen(buf)] = '\n';
        int fd = open("./fifo_cmd",O_RDWR);
        if(write(fd,buf,strlen(buf)) == -1){
            qDebug() << "error";
            return;
        }
        ::close(fd);
}

void Widget::qiefun()//切换歌曲
{
    timer->stop();
    timebef = 0;
    timer->start(1000);
    maps.clear();
    ui->listWidget_2->clear();
    ui->listWidget_2->verticalScrollBar()->setSliderPosition(0);
    if(index < 0){
        index = maxindex;
    }else if(index == maxindex + 1){
            index = 0;
    }
     ui->listWidget->setCurrentRow(index);
     mygqname = ui->listWidget->item(index)->text();
     QString s = "loadfile  /home/zjr/znyx/song/" + ui->listWidget->item(index)->text();
     bfyyfun(s.toUtf8().data());
     wTime();
     getTimeLen();
     tag = 1;
     ui->bfbtn->setStyleSheet(tr("border-image: url(:/img/pause1.png);"));
     gcshow();
     getgc(NULL,0);
}

void Widget::getTimeLen()
{
//    QMessageBox::about(this,"111",QString::number(timeaft));

    usleep(500000);
    QString m = QString::number(timeaft / 60);
    QString s = QString::number(timeaft % 60);
    if((timeaft / 60) < 10 ){
       m = "0" + m;
    }
    if((timeaft % 60) < 10 ){
        s = "0" + s;
    }
    QString str = m + ":" + s;
    ui->time2->setText(str);

}


void Widget::wTime()
{
    bfyyfun("get_time_length");
}

void Widget::timefun()
{
    if(timebef >= timeaft){
        index++;
        qiefun();
    }
}

void Widget::getgc(char *lists, int num)
{
    ui->listWidget_2->clear();
    ui->listWidget_2->verticalScrollBar()->setSliderPosition(0);
    //遍历map容器

            ui->listWidget_2->addItem("     咕咚音乐陪你每一刻");
            ui->listWidget_2->addItem("");
            ui->listWidget_2->addItem("");
            for ( map<int, QString>::iterator it = maps.begin(); it != maps.end(); ++it) {

                ui->listWidget_2->addItem(it->second);
                // 获取当前值
            }
}

void Widget::gcshow()
{
    int num = 0;
    maps.clear();
    DIR *dir = opendir("/home/zjr/znyx/lyrics");
    if(dir == NULL){
        printf("error\n");
        return;
    }
    while (1) {
        struct dirent * d = readdir(dir);
        if(d == NULL){
            break;
        }
        if(d->d_type == DT_REG){
            QString dirstr = d->d_name;
            QStringList liststr =  dirstr.split(".");
            QStringList gqstr = mygqname.split(".");
            if(liststr.first() == gqstr.first()){
                QString str = "/home/zjr/znyx/lyrics/" + gqstr.first() + ".lrc";
                FILE *f = fopen(str.toUtf8().data(), "r");
                    if (f == NULL)
                    {
                        printf("文件不存在\n");
                        return;
                    }
                    fseek(f, 0, 2);
                    int len = ftell(f);
                    rewind(f);
                    char *lrcstr = (char *)malloc(len + 1);
                    if(lrcstr == NULL){
                        return ;
                    }
                       fread(lrcstr, len, 1, f);

                        char *gclist[200] = {0};
                        gclist[0] = strtok(lrcstr,"\r\n");
                        num =0;
                        while(gclist[num] != NULL){
                            num++;
                            gclist[num] = strtok(NULL,"\r\n");
                        }

                        QString s2 = gclist[1];
                        QString s3 = QString::fromUtf8(gclist[2]);
                        QString zj = "专辑:"+s3.mid(4,s3.length()-5);
                        QString gs = "  歌手:"+s2.mid(4,s2.length()-5);
                        ui->gqname->setText(gqstr.first());
                        ui->gsname->setText(zj+gs);
                        ui->gqname->setStyleSheet("color: #F5F5F5");
                        ui->gsname->setStyleSheet("color: #A5AA55");

                        int m,s,ms;
                           char *strs;
                           int timenum = 0;
                           int timearr[10];
                           QString jhg = " ";
                        for(int i = 4;i < num;i++){
                            strs = gclist[i];
                            if(strs != NULL){
                                timenum = 0;
                                while(*strs == '['){

                                      sscanf(strs,"[%2d:%2d.%2d",&m,&s,&ms);
                                      timearr[timenum] = m * 60 + s;
                                      timenum = timenum+1;
                                      strs = strs + 10;
                                 }
                            }
                            for(int j = 0;j < timenum; j++){
                                if(strs != NULL){
                                    jhg = jhg + " ";
                                    qDebug()<< strs;
                                    map<int,QString>::iterator it = maps.find(timearr[j]);
                                    if(it != maps.end()){
                                        maps.insert(make_pair(timearr[j]+1,strs+jhg));
                                    }else{
                                        maps.insert(make_pair(timearr[j],strs+jhg));
                                    }

                                }


                            }

                        }
                        if(lrcstr != NULL){
                            free(lrcstr);
                            lrcstr = NULL;
                        }
                        fclose(f);

            }
        }
    }
    closedir(dir);
    return ;
}

void Widget::showgc(int timels)
{
    //遍历map容器
    map<int, QString>::iterator it = maps.begin();
            for (; it != maps.end(); ++it) {
                    if(timels == it->first){
                        int j = 0;
                        for(int i = 0 ;i < ui->listWidget_2->count();i++){
                            if(ui->listWidget_2->item(i)->text() == it->second){
                                j++;
                               ui->listWidget_2->setCurrentRow(i);
                               ui->listWidget_2->verticalScrollBar()->setMaximum(ui->listWidget_2->count());
                               ui->listWidget_2->verticalScrollBar()->setSliderPosition(i-3);
                            }
                        }
                    }
            }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_listWidget_itemClicked(QListWidgetItem *item)//列表点击事件
{

    //获取选中的item在qlistwidget中的位置
    index = ui->listWidget->currentRow();
    //获取item中的内容
    QString s = "loadfile  /home/zjr/znyx/song/" + item->text();
    mygqname = item->text();
//    bfyyfun(s.toUtf8().data());
    qiefun();
}

void Widget::on_bfbtn_clicked()//暂停/取消暂停
{
    if(tag == 2){
        tag = 1;
        ui->bfbtn->setStyleSheet(tr("border-image: url(:/img/pause1.png);"));

        timer->start(1000);
        qiefun();
        wTime();
        getTimeLen();
        gcshow();
        getgc(NULL,0);
    }
    else if(tag == 1){
        tag = 0;
        ui->bfbtn->setStyleSheet(tr("border-image: url(:/img/play1.png);"));
        timer->stop();
        bfyyfun("pause");
    }else if (tag == 0){
        tag = 1;
        timer->start(1000);
        ui->bfbtn->setStyleSheet(tr("border-image: url(:/img/pause1.png);"));
        bfyyfun("pause");
    }

}
void Widget::on_lbtn_clicked()//上一首
{
    index--;
    timebef = 0;
    qiefun();
}

void Widget::on_rbtn_clicked()//下一首
{
    index++;
    timebef = 0;
    qiefun();
}

void Widget::on_ybtn_clicked()//静音开关
{
    if(flag){
        flag = 0;
        ui->ybtn->setStyleSheet(tr("border-image: url(:/img/mute1.png);"));
        bfyyfun("mute 0");
    }else{
        flag = 1;
        ui->ybtn->setStyleSheet(tr("border-image: url(:/img/mute0.png);"));
        bfyyfun("mute 1");
    }
}

void Widget::on_horizontalSlider_2_valueChanged(int value)//设置音量
{
    QString s = "volume  " + QString::number(value) + " 1";
    bfyyfun(s.toUtf8().data());
}

void Widget::setTime()
{
    timebef++;
    timefun();
    QString m = QString::number(timebef / 60);
    QString s = QString::number(timebef % 60);
    if((timebef / 60) < 10 ){
       m = "0" + m;
    }
    if((timebef % 60) < 10 ){
        s = "0" + s;
    }
    QString str = m + ":" + s;
    ui->time1->setText(str);
    ui->horizontalSlider->setValue(timebef); // 获取当前时间（以秒为单位）
    ui->horizontalSlider->setMaximum(timeaft);
    ui->horizontalSlider->setMinimum(0);
    showgc(timebef);
}

void Widget::onStudyValueChanged(int num)
{
    if (ui->listWidget_2->verticalScrollBar()->minimum() == num) {
           qDebug()<<"滚动条最顶部"<<num;
       }

       if (ui->listWidget_2->verticalScrollBar()->maximum() == num) {
           qDebug()<<"滚动条最底部"<<num;
       }
}


void Widget::on_horizontalSlider_sliderReleased()
{
    timebef = ui->horizontalSlider->value();
    QString s = "seek  " + QString::number(timebef) + " 2";
    bfyyfun(s.toUtf8().data());
}

void Widget::on_listWidget_2_indexesMoved(const QModelIndexList &indexes)
{

}
